package com.example.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.Admin;
import com.example.demo.exception.BusinessException;
import com.example.demo.result.ResponseCode;
import com.example.demo.result.Result;
import com.example.demo.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name="管理员信息管理")
@RestController
public class AdminController {
    @Resource
    private AdminService adminService;

    @Operation(summary = "新增管理员")
    @PostMapping("/admin/add")
    public Result add(@RequestBody Admin admin) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, admin.getUsername());
        long count = adminService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ResponseCode.USERNAME_EXIST);
        }
        adminService.save(admin);
        return Result.success();
    }

    @Operation(summary = "管理员信息列表")
    @PostMapping("/admin/list")
    public Result<PageInfo<Admin>> list(@RequestBody Admin admin,@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<Admin>();
        queryWrapper.like(admin.getName()!=null,Admin::getName,admin.getName());
        queryWrapper.like(admin.getTel()!=null,Admin::getTel,admin.getTel());
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list =adminService.list();
        PageInfo<Admin> pageInfo = new PageInfo<>(list);
        return Result.data(pageInfo);
    }

    @Operation(summary = "修改管理员")
    @PostMapping("/admin/update")
    public Result update(@RequestBody Admin admin) {
        adminService.updateById(admin);
        return Result.success();
    }

    @Operation(summary = "删除管理员")
    @PostMapping("/admin/delete")
    public Result delete(@RequestParam long id) {
        adminService.removeById(id);
        return Result.success();
    }
}
